﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESRI.ArcGIS;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Server;
using ESRI.ArcGIS.Framework;

using mapXBase;
using mc_basXcls7Lib;
using mc_basObj7Lib;
using mx_MapLibCtrlLib;
using System.Collections;

namespace ConvertProject
{
    class PntConvert
    {
        //收集已经使用过的子图
        //public List<IStyleGalleryItem> list = new List<IStyleGalleryItem>();
        StyleSymbolMap mStyleSymbolMap = null;
        public void SetStyleSymbolMap(StyleSymbolMap styleSymbolMap)
        {
            mStyleSymbolMap = styleSymbolMap;
        }


        //读取WT信息并转换  GCScode坐标系
        public void readWT(IXGroupLayer grouplayer, string groupname, IMap imap, string savepath, IMapDocument m_MapDocument, string stylepath, int GCScode)
        {
            //读取点图层信息
            IXMapLayer wtlayer = grouplayer.get_Layer(2);
            //MessageBox.Show(groupname);
            string layername = groupname.Substring(0, groupname.Length - 3);
            layername = layername + "_Pnt";

            //获取图层简单要素类
            ISFeatureCls m_sfcls = wtlayer.XClass as mcSFeatureCls;

            //查询属性记录  点的总数 以及objectid
            mcRecordSet recordset = null;
            m_sfcls.Select(null, out recordset);
            if (recordset == null)
            {
                return;
            }
            recordset.MoveFirst();

            IGeomInfo info = null;
            mc_basObj7Lib.IGeometry itry = null;
            mcRecord record = null;
            mcObjectID id = new mcObjectID();


            /************************************************************************/
            /* 生成shapefile文件                                                    */

            ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);

            IAoInitialize m_iao = new AoInitializeClass();
            m_iao.Initialize(esriLicenseProductCode.esriLicenseProductCodeEngineGeoDB);

            //const string strFolder = @"D:\MXD1"; 　　//目标文件夹
            string strName = layername;　　//文件名
            const string strShapeFieldName = "Shape";

            //Open the folder to contain the shapefile as a workspace
            IFeatureWorkspace pFWS;
            IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();
            pFWS = pWorkspaceFactory.OpenFromFile(savepath, 0) as IFeatureWorkspace;

            //Set up a simple fields collection
            ESRI.ArcGIS.Geodatabase.IFields pFields = new FieldsClass();　　//字段
            IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;

            //Make the shape field
            //it will need a geometry definition, with a spatial reference
            ESRI.ArcGIS.Geodatabase.IField pField = new FieldClass();
            IFieldEdit pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Name_2 = strShapeFieldName;
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;

            IGeometryDef pGeometryDef = new GeometryDef();
            IGeometryDefEdit pGeometryDefEdit = pGeometryDef as IGeometryDefEdit;
            pGeometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;

            //************设置坐标系 *********
            ISpatialReferenceFactory2 ipSpaRefFact2 = new SpatialReferenceEnvironmentClass();
            IGeographicCoordinateSystem ipGeoCoordSys = new GeographicCoordinateSystemClass();
            if (GCScode != 0)
            {
                ipGeoCoordSys = ipSpaRefFact2.CreateGeographicCoordinateSystem(GCScode);
                pGeometryDefEdit.SpatialReference_2 = ipGeoCoordSys as ISpatialReference;
            } 
            else
            {
                pGeometryDefEdit.SpatialReference_2 = new UnknownCoordinateSystem() as ISpatialReference;
            }
            //************设置坐标系 *********
            pFieldEdit.GeometryDef_2 = pGeometryDef;
            pFieldsEdit.AddField(pField);

            //添加字段        
            mcFields fields;
            recordset.GetFields(out fields);
            short numfields = fields.numbfield;
            for (short i = 0; i < numfields; i++)
            {
                mcField field = fields.get_fldEntry(i);
                pField = new FieldClass();
                pFieldEdit = pField as IFieldEdit;
                pFieldEdit.Length_2 = 15;
                pFieldEdit.Name_2 = field.fieldname;
                pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                pFieldsEdit.AddField(pField);
            }

            //Add OID field
            pField = new FieldClass();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Length_2 = 15;
            pFieldEdit.Name_2 = "IDS";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            pFieldsEdit.AddField(pField);

            //Add SubNo field
            pField = new FieldClass();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Length_2 = 15;
            pFieldEdit.Name_2 = "SubNo";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
            pFieldsEdit.AddField(pField);

            //Add SubHeight field
            pField = new FieldClass();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Length_2 = 15;
            pFieldEdit.Name_2 = "SubHeight";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
            pFieldsEdit.AddField(pField);

            //Add SubWidth field
            pField = new FieldClass();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Length_2 = 15;
            pFieldEdit.Name_2 = "SubWidth";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
            pFieldsEdit.AddField(pField);

            //Add SubAngle field
            pField = new FieldClass();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Length_2 = 15;
            pFieldEdit.Name_2 = "SubAngle";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
            pFieldsEdit.AddField(pField);


            //Add TrueAngle field
            pField = new FieldClass();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Length_2 = 15;
            pFieldEdit.Name_2 = "TrueAngle";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeSingle;
            pFieldsEdit.AddField(pField);

            //Add SubColor field
            pField = new FieldClass();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Length_2 = 15;
            pFieldEdit.Name_2 = "SubColor";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
            pFieldsEdit.AddField(pField);

            //Add SubLayer field
            pField = new FieldClass();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Length_2 = 15;
            pFieldEdit.Name_2 = "SubLayer";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
            pFieldsEdit.AddField(pField);
            
            /**额外添加字段**/
            pField = new FieldClass();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Length_2 = 150;
            pFieldEdit.Name_2 = "GEONAME";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            pFieldsEdit.AddField(pField);

            pField = new FieldClass();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Length_2 = 60;
            pFieldEdit.Name_2 = "SIPNAME";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            pFieldsEdit.AddField(pField);

            pField = new FieldClass();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Length_2 = 15;
            pFieldEdit.Name_2 = "GEOCODE";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
            pFieldsEdit.AddField(pField);

            pField = new FieldClass();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Length_2 = 8;
            pFieldEdit.Name_2 = "GEOOBJNUM";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            pFieldsEdit.AddField(pField);

            pField = new FieldClass();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Length_2 = 20;
            pFieldEdit.Name_2 = "SHOWLEVEL";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
            pFieldsEdit.AddField(pField);

            /**额外添加字段**/

            //Create the shapefile

            IFeatureClass featureClass = pFWS.CreateFeatureClass(strName, pFields, null, null, esriFeatureType.esriFTSimple, "Shape", "");

            /************************************************************************************************************************/

            int pntcount = recordset.count;
            for (int j = 0; j < pntcount; j++)
            {
                /*********************向shapefile文件插入记录***********************/
                IFeatureCursor pInsertFeatureCursor;
                pInsertFeatureCursor = featureClass.Insert(true);

                IFeatureBuffer pInsertFeatureBuffer;
                pInsertFeatureBuffer = featureClass.CreateFeatureBuffer();
                /*********************向shapefile文件插入记录***********************/

                //获取对象的id号   OID
                recordset.GetID(out id);
                recordset.MoveNext();
                pInsertFeatureBuffer.set_Value(featureClass.FindField("IDS"), id.String);
                //获取线文件的属性，图形参数和线对应的坐标。
                m_sfcls.Get(id, out itry, out record, out info);

                //图形参数
                IPntInfo pntinfo = (IPntInfo)info;
                pInsertFeatureBuffer.set_Value(featureClass.FindField("SubNo"), pntinfo.symID);
                pInsertFeatureBuffer.set_Value(featureClass.FindField("SubHeight"), pntinfo.height);
                pInsertFeatureBuffer.set_Value(featureClass.FindField("SubWidth"), pntinfo.width);
                pInsertFeatureBuffer.set_Value(featureClass.FindField("SubAngle"), pntinfo.angle);
                pInsertFeatureBuffer.set_Value(featureClass.FindField("SubColor"), pntinfo.outclr1);
                pInsertFeatureBuffer.set_Value(featureClass.FindField("TrueAngle"), null);
                pInsertFeatureBuffer.set_Value(featureClass.FindField("SubLayer"), null);


                //点对应的坐标
                IGeoPoints lintry = (IGeoPoints)itry;
                mc3Dots dots = null;
                lintry.GetDots(out dots);

                double x, y, z;
                dots.Get(0, out x, out y, out z);
                //MessageBox.Show(x + "   " + y);

                //点的属性信息
                mcFields fields1;
                record.GetFields(out fields1);
                //每个点对应的属性
                for (int i = 0; i < fields1.numbfield; i++)
                {
                    mcField field = fields1.get_fldEntry((short)i);
                    string name = field.fieldname; //属性字段名

                    string strout;                 //属性字段值
                    meFieldType metype;           //属性字段类型
                    short isnull;              //字段是否为空
                    record.CvtFldToString(name, out strout, out metype, out isnull);

                    //pInsertFeatureBuffer.set_Value(featureClass.FindField(name), strout);
                    pInsertFeatureBuffer.set_Value(i+2, strout);

                    //  strout 为字段值  name  为字段名
                }



                /*********************向shapefile文件插入记录***********************/
                //MessageBox.Show(featureClass.FindField("SubNo") + "");

                IPoint pPoint = new ESRI.ArcGIS.Geometry.Point();
                pPoint.X = x;
                pPoint.Y = y;
                pInsertFeatureBuffer.Shape = pPoint;

                //InsertFeature
                pInsertFeatureCursor.InsertFeature(pInsertFeatureBuffer);
                pInsertFeatureCursor.Flush();
                /*********************向shapefile文件插入记录***********************/
            }

            //向MXD中添加图层
            IFeatureLayer pFeatureLayer = new FeatureLayerClass();
            pFeatureLayer.FeatureClass = featureClass;
            pFeatureLayer.Name = strName;
            ILayer ilayer = (ILayer)pFeatureLayer;
            imap.AddLayer((ILayer)pFeatureLayer);

            //渲染
            PntRender(savepath, strName, featureClass, ilayer,stylepath);

            //m_MapDocument.Save();
            //System.GC.Collect();
            //m_iao.Shutdown();
        }
        
        //点渲染
        private void PntRender(string savepath, string strName, IFeatureClass featureClass, ILayer ilayer, string stylepath)
        {
            //生成lyr文件
            ILayerFile layerfile = new LayerFileClass();
            string filename = savepath + "\\" + strName + ".lyr";
            layerfile.New(filename);

            //生成渲染对象
            IUniqueValueRenderer render = new UniqueValueRendererClass();
            IQueryFilter queryfileter = new QueryFilterClass();
            IFeatureCursor featurecursor = featureClass.Search(queryfileter, false);

            //创建简单符号
            IMarkerSymbol simplemarkersymbol;

            //渲染字段设置
            string fillname = "IDS";
            render.FieldCount = 1;
            render.set_Field(0, "IDS");

            //颜色
            IRgbColor rgcolor;

            //得到点数
            int pntcount = featureClass.FeatureCount(queryfileter);

            //字段编号 渲染使用
            ESRI.ArcGIS.Geodatabase.IFields fields = new FieldsClass();
            int idfield = 0;
            int subnofield = 0;
            int subcolorfield = 0;
            int subwidthfield = 0;
            int subanglefield = 0;

            fields = featurecursor.Fields;
            idfield = fields.FindField("IDS");
            subnofield = fields.FindField("SubNo");
            subcolorfield = fields.FindField("SubColor");
            subwidthfield = fields.FindField("SubWidth");
            subanglefield = fields.FindField("SubAngle");

            //遍历记录
            IFeatureBuffer featurebuff = featureClass.CreateFeatureBuffer();
            for (int i = 0; i < pntcount; i++)
            {
                //下移遍历整个dbf
                featurebuff = (IFeatureBuffer)featurecursor.NextFeature();

                //获取各字段值
                string id = (string)featurebuff.get_Value(idfield);
                int subno = (int)featurebuff.get_Value(subnofield);
                int subcolor = (int)featurebuff.get_Value(subcolorfield);
                double subwidth = (double)featurebuff.get_Value(subwidthfield);
                double subangle = (double)featurebuff.get_Value(subanglefield);

                //创建简单符号
                simplemarkersymbol = new SimpleMarkerSymbolClass();

                //将获取的颜色号转为rgb
                /************************************************************************/
                IXMapColorLib clib = new mcMapColorLibClass();
                if (subcolor == 0)
                {
                    subcolor = 1;
                }
                //MessageBox.Show("颜色库中颜色数量："+clib.ColorNum);
                mcMapColor col = clib.get_MapColor(subcolor);
                mcColorRGB pntcol = col.RGBValue;
                /************************************************************************/
                //将颜色值赋给的颜色对象
                rgcolor = new RgbColorClass();
                rgcolor.Red = pntcol.Red;
                rgcolor.Green = pntcol.Green;
                rgcolor.Blue = pntcol.Blue;
                //MessageBox.Show("dbf字段："+id + "" + fillcolor + "  " + patno + "  " + patnocolor);

                if(subno != 0)
                {

                    //style渲染
                    //加载指定的symbol    style文件  名称格式化
                    string stylename = "P-" + String.Format("{0:0000}", subno);

                    //创建symbol
                    //IStyleGalleryItem stlitem = new StyleGalleryItemClass();
                    //IEnumStyleGalleryItem enumitem = new EnumServerStyleGalleryItemClass();

                    //enumitem = styleGallery.get_Items("Marker Symbols", stylepath, "");
                    
                    //enumitem.Reset();
                    //stlitem = enumitem.Next();

                    ISymbol symbol = new PictureMarkerSymbolClass();
                    bool flagexist = false;
                   
                    symbol = mStyleSymbolMap.GetMarkerSymbol(stylename);
                    flagexist = (symbol != null);

                    ////首先遍历list
                    //if (list.Count == 0)
                    //{
                    //    while (stlitem != null)
                    //    {
                    //        string name = stlitem.Name;
                    //        if (name.Equals(stylename))  //名称匹配返回
                    //        {
                    //            symbol = (ISymbol)stlitem.Item;
                    //            list.Add(stlitem);
                    //            flagexit = true;
                    //            break;
                    //        }
                    //        stlitem = enumitem.Next();
                    //    }
                    //}
                    //else
                    //{
                    //    //遍历list
                    //    for (int m = 0; m < list.Count; m++)
                    //    {
                    //        if (list[m].Name.Equals(stylename))
                    //        {
                    //            symbol = (ISymbol)list[m].Item;
                    //            flagexit = true;
                    //            break;
                    //        }
                    //    }
                    //    //如果list中不存在，就去style文件中遍历。
                    //    if (!flagexit)
                    //    {
                    //        while (stlitem != null)
                    //        {
                    //            string name = stlitem.Name;
                    //            if (name.Equals(stylename))  //名称匹配返回
                    //            {
                    //                symbol = (ISymbol)stlitem.Item;
                    //                list.Add(stlitem);
                    //                flagexit = true;
                    //                break;
                    //            }
                    //            stlitem = enumitem.Next();
                    //        }
                    //    }
                    //}
                                      
                    //遍历sytle 
                    /**while (stlitem != null)
                    {
                        string name = stlitem.Name;
                        if (name.Equals(stylename))  //名称匹配返回
                        {
                            symbol = (ISymbol)stlitem.Item;
                            flagexit = true;
                            break;
                        }
                        stlitem = enumitem.Next();
                    }**/

                    //渲染使用子图在style中存在与不存在的处理
                    if (flagexist)
                    {

                        //图案渲染
                        IMarkerSymbol markersymbol = (IMarkerSymbol)symbol;
                        markersymbol.Color = rgcolor;   //颜色
                        markersymbol.Size = subwidth/0.35278;  //大小
                        markersymbol.Angle = subangle;  //角度

                        //WriteLogFile(id + "   " + patno);
                        render.AddValue(id, fillname, (ISymbol)markersymbol);
                        render.set_Label(id, id);
                        render.set_Symbol(id, (ISymbol)markersymbol);
                    } 
                    else
                    {
                        //简单渲染 
                        simplemarkersymbol.Color = rgcolor;
                        simplemarkersymbol.Size = subwidth / 0.35278;
                        simplemarkersymbol.Angle = subangle;

                        render.AddValue(id, fillname, (ISymbol)simplemarkersymbol);
                        render.set_Label(id, id);
                        render.set_Symbol(id, (ISymbol)simplemarkersymbol);
                    }
                }
            }
            ilayer.Visible = true;
            IGeoFeatureLayer igeofeature = (IGeoFeatureLayer)ilayer;
            IFeatureRenderer featurerender = (IFeatureRenderer)render;
            igeofeature.Name = strName;
            igeofeature.Renderer = featurerender;
            igeofeature.DisplayField = fillname;

            layerfile.ReplaceContents(igeofeature);
            //layerfile.Save();

            layerfile.Close();
        }
     
    }
}
